//
// Created by suzhen on 17-1-4.
//

#include "HttpResponse.h"
#include "Utils.h"

USING_ORION_V2

void HttpResponse::writeBody(const std::string &bd) {
    body_ << bd;
}

void HttpResponse::writeHeader(const std::string &k, const std::string &v, bool forceOverride) {
    HttpHeaderType::iterator it = headers_.find(k);
    if (headers_.find(k) != headers_.end()) {
        //not exist
        if (forceOverride) {
            headers_.erase(it);
            goto insertPos;
        }
    }
    insertPos:
    headers_.emplace(std::make_pair(k, v));
}

std::string HttpResponse::buildHttpText() {
    std::string bodyStr = body_.str();
    std::ostringstream oss;
    oss << "HTTP/1.1 " << httpCode_ << " Hello\r\n";
    oss << "Server: OrionV2-Embed-Server\r\n";
    oss << "Content-Type: " << contentType_ << "\r\n";
    oss << "Content-Length: " << bodyStr.size() << "\r\n";

    std::for_each(headers_.begin(), headers_.end(),
                  [&](std::pair<const std::string, std::string> &itm) {
                      oss << Utils::sformat("%1%: %2%\r\n", itm.first, itm.second);
                  });
    oss << "\r\n";
    oss << bodyStr;
    return oss.str();
}

void HttpResponse::setStatusCode(unsigned int code) {
    httpCode_ = code;
}

void HttpResponse::setContentType(const std::string &ctp) {
    contentType_ = ctp;
}

std::ostream &HttpResponse::getOutPutStream() {
    return body_;
}

HttpResponse::HttpResponse(int httpCode,
                           const std::string &contentType,
                           const HttpHeaderType &headers) :
        httpCode_(httpCode),
        contentType_(contentType),
        headers_(headers) {
}


